<template>
  <div class="home">
    <div class="detail_box" style="min-height: auto;min-width:auto">
      <!-- 菜单 -->
      <div class="tab_menu" v-if="userType==1||userType==5 ||userType==0">
        <div>
          <span v-for="(item,index) in oneMenus" :class="{'choose':index===tabIndex}" @click="chooseTab(index)">{{userType== 1|| userType== 0? (index==0 ? '待审阅价格' : '全部商品'):item}}</span>
        </div>
      </div>
      <!-- 销售主管菜单 -->
      <div class="tab_menu" v-if="userType==4">
        <div>
          <span v-for="(item,index) in twoMenus" :class="{'choose':index===tabIndex}" @click="chooseTab(index)">{{item}}</span>
        </div>
      </div>
<!--       操作 -->
      <div class="operate_box">
        <div class="item_box">
          <div class="operate_item">
            <label>关键词：</label>
            <el-input type="text" clearable placeholder="请输入关键词" v-model="keyword"></el-input>
          </div>
          <div class="operate_item"  v-if="!$route.query.userId">
            <label>用户：</label>
            <userSelect @listenToUser="getUserId" :uId="user"/>
          </div>
          <div class="operate_item" v-if="isEnable">
            <label>状态：</label>
            <el-select
              filterable
              clearable
              v-model="mIndex"
              placeholder="请选择状态">
              <el-option
                v-for="(item,index) in statusOption"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="operate_item">
            <span class="operate_btn search_btn" @click="getTableInfo(1)">查询</span>
            <span class="operate_btn reset_btn" @click="resetTable">重置</span>
          </div>
        </div>
        <div class="flex_box">
          <div class="btn_box" v-if="btn&&btn.add">
            <span class="operate_btn search_btn" @click="openPopup('',1)">新增</span>
          </div>
<!--          <div class="btn_box" v-if="btn&&btn.entry">-->
<!--            <span class="operate_btn import_btn" @click="openPopup('',5)">录入</span>-->
<!--          </div>-->
        </div>
      </div>
      <!-- 表格 -->
      <div class="table_box">
        <el-table
          border
          max-height='auto'
          v-loading="loading"
          :header-cell-style="tableHeader"
          ref="multipleTable"
          :data="tableInfo"
          tooltip-effect="dark"
          style="width: 100%;">
          <el-table-column
            width="80"
            prop="id"
            label="ID">
          </el-table-column>
          <el-table-column
            width="160"
            sortable
            prop="modifyTime"
            label="修改时间">
            <template slot-scope="scope">{{ formatTime(scope.row.modifyTime) }}</template>
          </el-table-column>

          <el-table-column
            label="用户名">
            <template slot-scope="scope"><p @click="showPepole(scope.row)">
              {{ scope.row.userName ? scope.row.userName : '——' }}{{scope.row.remark ? `(${scope.row.remark})` : ''}}</p></template>
          </el-table-column>

          <el-table-column
            prop="productName"
            label="商品名称">
          </el-table-column>
          <el-table-column
            width="80"
            label="商品图片">
            <template slot-scope="scope">
              <div>
                <img :src="scope.row.productPhoto" class="icon" v-if="scope.row.productPhoto">
                <p v-else>——</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="price"
            label="购买价格(元)">
          </el-table-column>
          <el-table-column
            sortable
            prop="originalPrice"
            label="原价(元)">
          </el-table-column>

          <el-table-column
            label="起送量">
            <template slot-scope="scope">
              <p>{{ scope.row.minSendNumber ? scope.row.minSendNumber : 0 }}</p></template>
          </el-table-column>

          <el-table-column
            sortable
            prop="numbers"
            label="可用量">
          </el-table-column>
          <el-table-column
            width="160"
            prop="usedAuthNumber"
            label="可/已使用授权额度">
            <template slot-scope="scope">
              <p>
                <span style="color: #f7ab20">{{ scope.row.authNumber }}</span> / <span
                style="color: #bbbbbb">{{ scope.row.usedAuthNumber }}</span>
              </p>
            </template>
          </el-table-column>

          <el-table-column
            width="80"
            label="状态">
            <template slot-scope="scope">
              <div :style="'color:'+(scope.row.enable===1?'#67c430':(scope.row.enable===0?'#e60000':'orange'))">
                <p v-for="(item,index) in statusOption" :key="index" v-if="scope.row.enable===item.id">
                  {{ item.name }}</p>
              </div>
            </template>
          </el-table-column>

<!--          <el-table-column-->
<!--            label="启用/禁用"-->
<!--            prop="2"-->
<!--            width="100" v-if="(btn.freeze||btn.unfreeze)">-->
<!--            <template slot-scope="scope">-->
<!--              <div v-if="(btn.freeze||btn.unfreeze)&& (scope.row.enable != 2 ||!scope.row.enable != 3)">-->
<!--                <el-switch-->
<!--                  :active-value="1"-->
<!--                  :inactive-value="0"-->
<!--                  active-color="#13ce66"-->
<!--                  inactive-color="#ff4949"-->
<!--                  @change="deleteItem(scope.row,scope.$index)"-->
<!--                  v-model="scope.row.enable">-->
<!--                </el-switch>-->
<!--                <span class="normal" v-if="scope.row.enable===1">启用</span>-->
<!--                <span class="unusual" v-else>禁用</span>-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-table-column>-->

          <el-table-column
            label="操作"
            fixed="right"
            v-if="btn&&(btn.detail||btn.check||btn.setQuota||btn.emptyQuota||btn.changePrice || btn.log || btn.update || btn.review||btn.freeze ||btn.unfreeze)"
            width="240">
            <template slot-scope="scope">
              <div class="table_btn">

                <span class="change_info" @click="openPopup(scope.row,2)" v-if="btn.detail">详情</span>
<!--                <span class="change_info" @click="handleEdit(scope.row)" v-if="btn.update">编辑</span>-->
                <span class="change_info check_info" @click="openPopup(scope.row,3)"
                      v-if="btn.check&&scope.row.enable==2">价格审核</span>
                <span class="change_info check_info" @click="openPopup(scope.row,3)"
                      v-if="btn.review &&(scope.row.enable==2|| scope.row.enable==3)">价格审阅</span>
                <span class="change_info check_info" @click="openPopup(scope.row,3)"
                      v-if="btn.changePrice&&scope.row.enable==1"> 修改价格购买量 </span>

                <span class="change_info delete_btn" @click="deleteItem(scope.row,0)" v-if="btn.freeze&&scope.row.enable===1">冻结</span>
                <span class="change_info check_info" @click="deleteItem(scope.row,1)" v-if="btn.unfreeze&&scope.row.enable===0">解冻</span>

                <span class="change_info" @click="openPopup(scope.row,4)" v-if="btn.setQuota">设置额度</span>
                <span class="change_info" @click="changeNum(scope.row)" v-if="btn.emptyQuota">核销额度</span>
                <span class="change_info check_info" @click="goLog(scope.row)" v-if="btn.log">查看日志</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="record_page">
        <span class="page_count">共<i>{{ totals }}</i>条</span>
        <el-pagination
          @size-change="sizeChange"
          @current-change="getTableInfo"
          background
          :current-page="currentPage"
          :page-sizes="[15, 20, 30, 40]"
          :page-size="pageSize"
          layout="prev, pager, next, sizes,jumper"
          :total="totals">
        </el-pagination>
      </div>
    </div>
    <people v-if="isPeople" :userId="userId" @listenToChild="listenToEdit"></people>
    <detail v-if="isPop" :productId="productId" :name="productName" :option="statusOption"
            @listenToChild="isPop=false"></detail>
    <edit v-if="isEdit" :productId="productId" @listenToChild="listenToEdit"></edit>
    <checkPopup v-if="isCheck" :productId="productId" @listenToChild="listenToEdit"></checkPopup>
    <setQuota v-if="isSet" :pId="productId" @listenToChild="listenToEdit"></setQuota>
    <entry v-if="isEntry" @listenToChild="listenToEdit"></entry>
    <changeUserQuota v-if="isChange" :userId="userId" :quote="quote" :productId="productId"
                     @listenToChild="listenToEdit"></changeUserQuota>
    <editProduct v-if="isEditPro" :info="editInfo" @listenToChild="listenToEdit"></editProduct>
  </div>
</template>

<script>
import detail from "./detail";
import edit from './edit'
import checkPopup from "./checkPopup";
import setQuota from "./setQuota";
import changeUserQuota from "./changeUserQuota";
import userSelect from '../../../components/user/index'
import commons from "../../../utils/common";
import {listData, getStatus, updateEnable} from "@/api/data/user/product";
import {getBtn} from "@/utils/btnAuth";
import people from "../list/edit"
import entry from "./entry"
import editProduct from "./editProduct"
import {formatTree} from "@/utils/menuAuth";

export default {
  // props:['uId'],
  components: {
    checkPopup,
    detail,
    edit,
    setQuota,
    people,
    entry,
    changeUserQuota,
    editProduct,
    userSelect
  },
  data() {
    return {
      user: '',
      status: '',
      statusOption: [],
      keyword: '',
      currentPage: 1,
      pageSize: 15,
      totals: 0,
      loading: false,
      tableInfo: [],
      isPop: false,
      productId: '',
      productName: '',
      isEdit: false,
      isCheck: false,
      isSet: false,
      btn: {},
      isPeople: false,
      isEntry: false,
      isChange: false,
      userId: '',
      quote: '',
      isEditPro: false,
      editInfo: {},
      oneMenus:['全部商品','待审核价格'],
      twoMenus:['待审核价格','待审阅价格','全部商品'],
      tabIndex:0,
      mIndex:'',
      userInfo:'',
      userType:'',
      isEnable:false
    }
  },
  mounted() {
    //获取用户类型
    let info = localStorage.getItem('water_user')
    this.userInfo = info?JSON.parse(info).loginUser:'';
    this.userType = this.userInfo.type;
    if(this.userType==5) {
      this.mIndex = ''
      this.isEnable = true;
    }else if(this.userType == 4) {
      this.mIndex = 2
    }else if(this.userType == 0 || this.userType == 1){
      this.mIndex = -1;
    }
    this.getProductStatus();
    this.btn = getBtn();
    if (this.btn.query) {
      this.getTableInfo(1);
    }
  },
  methods: {
    chooseTab(index){
      this.isEnable = false;
      if(this.userType==5) {
        index == 0 ? this.mIndex = '' : this.mIndex = -1
        if(index==0) {
          this.isEnable = true;
        }
      }else if(this.userType == 1 || this.userType == 0) {
        index == 0 ? this.mIndex = -1 : this.mIndex = ''
        if(index==1) {
          this.isEnable = true;
        }
      }
      if(this.userType == 4) {
        index == 0 ? this.mIndex = 2 :(index==1 ? this.mIndex = 3 : this.mIndex = '')
          if(index==2) {
            this.isEnable = true;
        }
      }
      this.tabIndex = index;
      this.getTableInfo(1);
    },
    // 获取列表信息
    getTableInfo(page) {
      let that = this;
      that.loading = true;
      that.currentPage = page;
      let queryParams = {
        limit: that.pageSize,
        page: page,
        keyword: that.keyword,
        // enable:that.mIndex,
        userId: that.$route.query.userId?parseInt(that.$route.query.userId):that.user,
        enable: that.mIndex
      }
      listData(queryParams).then(res => {
        that.tableInfo = res ? res.list : [];
        that.totals = res ? res.count : 0;
        that.loading = false;
      }).catch((e) => {
        that.loading = false;
      });
    },
    handleEdit(obj) {
      this.isEditPro = true;
      this.editInfo = obj;
    },

    // 重置
    resetTable() {
      this.pageSize = 15;
      this.keyword = '';
      this.status = '';
      this.user = '';
      this.getTableInfo(1)
    },

    // 获取用户id
    getUserId(e) {
      this.user = e;
    },

    getProductStatus() {
      getStatus().then(res => {
        this.statusOption = res ? res : [];
      })
    },
    // 删除
    deleteItem(obj,type) {
      let that = this;
      that.$confirm('确定'+(type===0?'冻结':'解冻')+obj.productName+'?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = {id:obj.id,enable:type}
        return updateEnable(param);
      }).then(() => {
        that.getTableInfo(that.currentPage);
        that.$message.success('操作成功！');
      }).catch(() => {
        // console.product('fail')
      });
    },

    // // 删除
    // deleteItem(obj, index) {
    //   let that = this;
    //   that.$confirm('确定' + (obj.enable === 0 ? '禁用' : '启用') + obj.productName + '?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     let param = {id: obj.id, enable: obj.enable}
    //     return updateEnable(param);
    //   }).then(() => {
    //     that.getTableInfo(that.currentPage);
    //     that.$message.success({
    //       message: '操作成功！',
    //       duration: 1500
    //     });
    //   }).catch(() => {
    //     //重置
    //     that.tableInfo[index].enable = obj.enable == 0 ? 1 : 0;
    //   });
    // },
    showPepole(obj) {
      this.isPeople = true;
      this.userId = obj.userId
    },

    // 打开弹窗
    openPopup(obj, type) {
      if (type == 5) {
        this.isEntry = true;
      } else {
        type === 1 ? this.isEdit = true : (type === 2 ? this.isPop = true : (type === 3 ? this.isCheck = true : this.isSet = true));
      }
      this.productId = obj ? obj.id : '';
      this.productName = obj && obj.productName ? obj.productName : '';
    },
    //查看日志
    goLog(obj) {
      let that = this;
      let url = '/user/log';
      let parent = '用户管理';
      that.$router.push({
        path: url,
        query: {
          key:formatTree(parent,url),
          productId: obj.productId,
          userId: obj.userId,
          username:obj.productName,
        }
      })

    },

    listenToEdit(e) {
      this.isPeople = false;
      this.isEdit = false;
      this.isCheck = false;
      this.isSet = false;
      this.isEntry = false;
      this.isChange = false;
      this.isEditPro = false;
      if (e.refresh) {
        this.getTableInfo(this.currentPage);
      }
    },

    changeNum(obj) {
      this.userId = obj.userId;
      this.quote = obj.usedAuthNumber;
      this.productId = obj.productId;
      this.isChange = true;
    },

    formatTime(time) {
      return commons.formatTime(time)
    },

    sizeChange(val) {
      this.pageSize = val;
      this.getTableInfo(1)
    },

    // 设置table标题居中
    tableHeader({row, column, rowIndex, columnIndex}) {
      return 'background:#F0F2F5;color:#111;padding:10px 0;font-size:14px;font-weight:600'
    },
  }
}
</script>

<style scoped>
.check_info {
  color: #f7ab20;
}

.flex_box {
  display: flex;
}
</style>
